import config from '@/config'
import storage from '@/utils/storage'
import constant from '@/utils/constant'
import {
	login,
	logout,
	getInfo
} from '@/api/login'
import {
	getToken,
	setToken,
	removeToken
} from '@/utils/auth'

const baseUrl = config.baseUrl

const user = {
	state: {
		token: getToken(),
		name: storage.get(constant.name),
		sportsData: {
			date: "1710952804684", // 时间戳(Unix时间戳,毫秒数)
			totalTime: 0, // 今天运动的总时间 (分钟)
			totalTimeSet: 10 * 60, // 设置的单次运动的总时间 秒
		},
	},

	mutations: {
		SET_TOKEN: (state, token) => {
			state.token = token
		},
		SET_NAME: (state, name) => {
			state.name = name
			storage.set(constant.name, name)
		},
		SET_SPORTSDATA_DATE: (state, date) => {
			state.sportsData.date = date
		},
		SET_SPORTSDATA_TOTALTIME: (state, totaltime) => {
			state.sportsData.totaltime = totaltime
		},
		SET_SPORTSDATA_TOTALTIMESET: (state, totalTimeSet) => {
			state.sportsData.totalTimeSet = totalTimeSet
		},
		SET_SPORTSDATA_EYEHEALTHHABITS: (state, habits) => {
			state.sportsData.habits = habits
		}
	},

	actions: {
		// 登录
		Login({
			commit
		}, userInfo) {
			const username = userInfo.username.trim()
			const password = userInfo.password
			return new Promise((resolve, reject) => {
				login(username, password).then(res => {
					if (res) {
						setToken(res.token)
						commit('SET_TOKEN', res.token)
					}
					resolve()
				}).catch(error => {
					console.log(error)
					reject(error)
				})
			})
		},

		// 获取用户信息
		GetInfo({
			commit,
		}, userInfo) {
			return new Promise((resolve, reject) => {
				getInfo().then(res => {
					const username = userInfo.username || uni.getStorageSync("username")
					commit('SET_NAME', username)
					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		},

		// 退出系统
		LogOut({
			commit,
			state
		}) {
			return new Promise((resolve, reject) => {
				logout(state.token).then(() => {
					commit('SET_TOKEN', '')
					commit('SET_ROLES', [])
					commit('SET_PERMISSIONS', [])
					removeToken()
					storage.clean()
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		}
	}
}

export default user